package cn.hanyx.coder.design.pattern.behavioral.chain.demo01;

/**
 * HandlerChain
 *
 * @author hanyx
 * @date 2020/06/05
 */
public class HandlerChain {

    /**
     * 链头
     */
    private Handler head = null;

    /**
     * 链尾
     */
    private Handler tail = null;

    public void addHandler(Handler handler) {
        handler.setSuccessor(null);

        if (head == null) {
            head = handler;
            tail = handler;
            return;
        }

        /**
         * 第一次执行: tail = handler ; head.successor = handler
         *            head.successor == tail
         * 此后新增Handle时会操作tail 等于操作 head.successor对象, 并形成链表结构
         */
        tail.setSuccessor(handler);
        tail = handler;
    }

    public void handle() {
        /**
         * 执行链头的handle方法
         */
        if (head != null) {
            head.handle();
        }
    }
}
